package com.example.qing.filter;

import com.alibaba.fastjson.JSON;
import com.example.qing.pojo.Result;
import com.example.qing.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import netscape.javascript.JSObject;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;

import java.io.IOException;

@Slf4j
/*@WebFilter(urlPatterns = "/*")*/
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest) servletRequest;
        HttpServletResponse resp=(HttpServletResponse) servletResponse;

        String jwt=req.getHeader("token");
        log.info("拦截到了请求");

        String url =req.getRequestURL().toString();
        log.info("请求的url:{}",url);
        if(url.contains("login")){
            log.info("登录放行");
            filterChain.doFilter(servletRequest,servletResponse);
            return ;
        }

        if(!StringUtils.hasLength(jwt)){
            Result error=Result.error("NOT_LOGIN");
            String notLogin=JSON.toJSONString(error);
            resp.getWriter().write(notLogin);
            return;
        }

        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析失败");
            Result error=Result.error("NOT_LOGIN");
            String notLogin=JSON.toJSONString(error);
            resp.getWriter().write(notLogin);
            return;
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
